#include "medialocatorsettings.h"
#include "ui_medialocatorsettings.h"
#include <Maestro/database.h>
#include <QtSql>

MediaLocatorSettings::MediaLocatorSettings(QWidget *parent) :
    SettingsMenuItem(parent),
    ui(new Ui::MediaLocatorSettings)
{
    ui->setupUi(this);
    loadFolders();
    locator=new MediaLocator();
    locator->start();
    addButton=new Button(QIcon(":/imgs/3F00Button_AddFolder.png"),"",this);
    addButton->setIconSize(QSize(256,48));
    addRow(addButton);
    ui->addFolderWidget->layout()->addWidget(addButton);
    QHBoxLayout * horizontalLayout=new QHBoxLayout();
    QList<Button *> * list=new QList<Button *>();
    saveButton = new Button(QIcon(":/imgs/3F00Button_Save.png"),"",this,NULL);
    saveButton->setIconSize(QSize(110,64));
    horizontalLayout->addWidget(saveButton);
    list->append(saveButton);
    cancelButton = new Button(QIcon(":/imgs/3F00Button_Cancel.png"),"",this);
    cancelButton->setIconSize(QSize(110,64));
    horizontalLayout->addWidget(cancelButton);
    list->append(cancelButton);
    addRow(list);
    ui->saveCancelWidget->setLayout(horizontalLayout);

}

MediaLocatorSettings::~MediaLocatorSettings()
{
    delete ui;
}

void MediaLocatorSettings::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void MediaLocatorSettings::loadFolders() {
    //removeButton(saveButton);
    QSqlQueryModel * model = Querier::getModel("SELECT * FROM ListenedFolders");
    for(int i=0; i<model->rowCount(); i++) {
        QWidget * widget=new QWidget(this);
        widget->setLayout(new QHBoxLayout());
        QLabel * label=new QLabel(model->record(i).value("path").toString());
        Button * button = new Button(QIcon(":/imgs/3F00Button_Remove.png"),"",this,widget);
        button->setIconSize(QSize(256,48));
        widget->layout()->addWidget(label);
        widget->layout()->addWidget(button);
        addRow(button);
        widget->layout()->setAlignment(button,Qt::AlignRight);
        ui->folderList->layout()->addWidget(widget);
    }
    /*QList<Button *> * list=new QList<Button *>();
    list->append(saveButton);
    list->append(cancelButton);
    addRow(list);*/
}

void MediaLocatorSettings::save() {

    foreach(QWidget * widget,recentlyRemoved) {
        if(widget) {
            for(int j=0; j<widget->children().size(); j++) {
                QLabel * label = qobject_cast<QLabel *>(widget->children().at(j));
                if(label) {
                    Button * button =qobject_cast<Button *>(widget->children().at(j+1));
                    if(button) {
                        qDebug()<<"kill";
                        QSqlQuery query=Querier::getResult("SELECT folderID FROM ListenedFolders WHERE path='"+label->text()+"'");
                        query.next();
                        long long id=query.value(0).toLongLong();
                        qDebug() <<"deleting folder with id: "<<id;
                        locator->removeFolder(label->text());
                        Querier::getResult("DELETE FROM ListenedFolders WHERE path='"+label->text()+"'");
                        Querier::getResult("DELETE FROM MediaFiles WHERE folderID='"+QString::number(id)+"'");
                    }
                }
            }
        }
    }
    recentlyRemoved.clear();

    foreach(QWidget * widget,recentlyAdded) {
        if(widget) {
            for(int j=0; j<widget->children().size(); j++) {
                QLabel * label = qobject_cast<QLabel *>(widget->children().at(j));
                if(label) {
                    Button * button =qobject_cast<Button *>(widget->children().at(j+1));
                    if(button) {
                        long long id=Querier::getResult("INSERT INTO ListenedFolders (path) VALUES('"+label->text()+"')").lastInsertId().toLongLong();
                        locator->addFolder(id,label->text());
                    }
                }
            }
        }
    }
    recentlyAdded.clear();
    locator->rescan();

    emit completed();
}

void MediaLocatorSettings::cancel() {
    while(getCurrentButton()) {
        removeButton(getCurrentButton());
    }
    while(recentlyRemoved.count()>0) {
        recentlyRemoved.first()->show();
        recentlyRemoved.removeFirst();
    }

    foreach(QObject * child, ui->folderList->children()) {
        QWidget * widget=qobject_cast<QWidget *>(child);
        if(widget) {
            for(int j=0; j<widget->children().size(); j++) {
                QLabel * label = qobject_cast<QLabel *>(widget->children().at(j));
                if(label) {
                    Button * button =qobject_cast<Button *>(widget->children().at(j+1));
                    if(button&&button->isVisible()) {
                        addRow(button);
                    }
                }
            }
        }
    }

    addRow(addButton);
    QList<Button *> * list=new QList<Button *>();
    list->append(saveButton);
    list->append(cancelButton);
    addRow(list);
    emit completed();
}

void MediaLocatorSettings::saveTest() {

}

void MediaLocatorSettings::assertSaved() {

}

void MediaLocatorSettings::cancelTest() {

}

void MediaLocatorSettings::assertCancelled() {

}

void MediaLocatorSettings::buttonSelected() {
    if(getCurrentButton()==saveButton) {
        save();
    } else if (getCurrentButton()==cancelButton) {
        cancel();
    } else if(getCurrentButton()==addButton) {
        QString dirName=QFileDialog::getExistingDirectory(this, tr("Open Directory"), "./",QFileDialog::ShowDirsOnly| QFileDialog::DontResolveSymlinks);
        if(dirName.size()>0) {
            QWidget * widget=new QWidget(this);
            widget->setLayout(new QHBoxLayout());
            QDir directory=QDir(qApp->applicationDirPath());
            #if defined(Q_OS_WIN)
                if (directory.dirName().toLower() == "debug" || directory.dirName().toLower() == "release")
                    directory.cdUp();
            #elif defined(Q_OS_MAC)
                    directory.cdUp();
                    directory.cdUp();
                    directory.cdUp();
            #endif
            if(dirName.startsWith(directory.absolutePath())) {
                dirName.replace(directory.absolutePath(),".");

            }
            QLabel * label=new QLabel(dirName);
            Button * button = new Button(QIcon(":/imgs/3F00Button_Remove.png"),"",this,widget);
            button->setIconSize(QSize(256,48));
            widget->layout()->addWidget(label);
            widget->layout()->addWidget(button);
            widget->layout()->setAlignment(button,Qt::AlignRight);
            addButtonBefore(button,addButton);
            ui->folderList->layout()->addWidget(widget);
            recentlyAdded.append(widget);
        }
    } else {
        QWidget * widget=qobject_cast<QWidget *>(getCurrentButton()->getItem());
        if(widget) {
            for(int j=0; j<widget->children().size(); j++) {
                QLabel * label = qobject_cast<QLabel *>(widget->children().at(j));
                if(label) {
                    widget->hide();
                    Button * button =qobject_cast<Button *>(widget->children().at(j+1));
                    if(button) {
                        removeButton(button);
                    }
                    recentlyRemoved.append(widget);
                }
            }
        }
    }
}
